import React from "react";
import AceEditor from "react-ace";
import PropTypes from "prop-types";
import Button from "antd/lib/button";
import Tooltip from "antd/lib/tooltip";
import Modal from "antd/lib/modal";
import { wrap as wrapDialog, DialogPropType } from "@/components/DialogWrapper";
import Visualization from "@/services/visualization"
import Link from "@/components/Link";
import "./EmbedDeveloperDialog.less";

import 'ace-builds/src-noconflict/mode-json'; // json模式的包
import "ace-builds/src-noconflict/theme-github";
import 'ace-builds/src-noconflict/ext-language_tools';

class EmbedDeveloperDialog extends React.Component {
  static propTypes = {
    dialog: DialogPropType.isRequired,
    query: PropTypes.object.isRequired, // eslint-disable-line react/forbid-prop-types
    visualization: PropTypes.object.isRequired, // eslint-disable-line react/forbid-prop-types
  };

  state = {
    userOptions: JSON.stringify(this.props.visualization.options, null, '\t'),
    isChange: false,
  };

  handleChange(value) {
    try {
      this.setState({
        userOptions: value,
        isChange: true,
      });    
    }
    catch {}
  }

  handleSave(dialog, visualization) {
    visualization.options = JSON.parse(this.state.userOptions.toString());
    Visualization.save(visualization).then(()=> {
      dialog.dismiss();    
      window.location.reload();
    });
  }

  render() {
    const { visualization, dialog } = this.props;

    return (
      <Modal
        {...dialog.props}
        maskClosable = {false}
        className="embed-query-dialog"
        title="高级配置"
        width={"75%"}
        footer={
          <React.Fragment>
            <Button key="save" disabled={!this.state.isChange} onClick={() => this.handleSave(dialog, visualization)}>保存</Button>
            <Button key="cancel" onClick={dialog.dismiss}>取消</Button>
          </React.Fragment>
        }>
        <AceEditor
          ref="editor" // 实例引用
          mode="json" // 模式
          theme="github" // 主题
          onChange={value => {
            this.handleChange(value);
          }}
          enableBasicAutocompletion //允许自动补全选项
          enableLiveAutocompletion
          enableSnippets
          name="UNIQUE_ID_OF_DIV" // 唯一明明
          value={this.state.userOptions}
          editorProps={{ $blockScrolling: true }}
          fontSize={16}
          width="100%"
          height="400px"
        />        
        <Link target="_blank" rel="noopener noreferrer" href="https://www.dazdata.com/docs/college/plotlyjs/1.html">
          <Tooltip title="在新窗口打开官网">plotly.js官网指南</Tooltip>
        </Link>
      </Modal>
    );
  }
}

export default wrapDialog(EmbedDeveloperDialog);
